#include "httpmgr.h"

#include <QJsonDocument>
#include <QByteArray>
#include <QNetworkReply>

HttpMgr::HttpMgr()
{
    //HTTP 收到响应后调用 slot_http_finish 函数
    connect(this, &HttpMgr::sig_http_finish, this, &HttpMgr::slot_http_finish);
}

HttpMgr::~HttpMgr()
{

}

// signals ----------------------------------------------------------

void HttpMgr::PostHttpReq(QUrl url, QJsonObject json_date, ReqId id, Modules mod)
{
    //将 json 转为字节数组
    QByteArray data = QJsonDocument(json_date).toJson();

    //设置 url
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(data.length()));

    //发送请求  返回值为指针类型，需要自己回收内存
    QNetworkReply* reply = this->_manager.post(request, data);

    //发送完成后发送后 异步 触发回调函数
    auto self = shared_from_this();
    QObject::connect(reply, &QNetworkReply::finished, [self, reply, id, mod](){
        QString res = "";

        //处理错误情况
        if(reply->error() != QNetworkReply::NoError)
        {
            qDebug() << __FILE__ << ":" << __LINE__
                     << reply->errorString() << " id:" << id << " mod:" << mod;
            //发射 sig_http_finish 信号
            emit self->sig_http_finish(id, mod, ErrorCode::ERR_NETWORK, std::move(res));
            //释放 reply 指针
            reply->deleteLater();
            return;
        }

        //读出所有数据
        res = reply->readAll();
        emit self->sig_http_finish(id, mod, ErrorCode::SUCCESS, std::move(res));
        reply->deleteLater();
        return;
    });

}

// slots ----------------------------------------------------------

void HttpMgr::slot_http_finish(ReqId id, Modules mod, ErrorCode err, QString res)
{
    //注册模块的信息 - RegisterDialog
    if(mod == Modules::REGISTER_MOD)
    {
        //发送信号到注册模块
        emit sig_reg_mod_finish(id, err, std::move(res));
    }
    if(mod == Modules::RESET_MOD)
    {
        //发送信号到修改密码模块
        emit sig_reset_mod_finish(id, err, std::move(res));
    }
    if(mod == Modules::LOGIN_MOD)
    {
        emit sig_login_mod_finish(id, err, std::move(res));
    }
}






















